﻿using System.ComponentModel;
using System.Web.UI;
using TA.JSON;
using System.Collections.Generic;

namespace TA.Turbo
{
	/// <summary>
	/// Template for HTML markup that is to be rendered more than once.
	/// </summary>
	[ParseChildren(true, "Template")]
	//[PersistChildren(false)]
	public class MultipleInstanceTemplate : MarkupTemplate
	{
		#region PUBLIC
		#region INIT
		/// <summary>
		/// Ctor.
		/// </summary>
		/// <param name="name"></param>
		public MultipleInstanceTemplate(string name)
			: base(name, TemplateInstance.Multiple)
		{
		}
		#endregion
		#region PROPS
		/// <summary>
		/// The template.
		/// </summary>
		[PersistenceMode(PersistenceMode.InnerDefaultProperty),
		TemplateContainer(typeof(ContainerControl)),
		MergableProperty(false),
		Browsable(false),
		TemplateInstance(TemplateInstance.Multiple)
		//, DesignerSerializationVisibility(DesignerSerializationVisibility.Content)
		]
		public ITemplate Template { get { return _template; } set { _template = value; } }
		#endregion
		#region METHODS
		/// <summary>
		/// Initializes this template by adding the proper include and instantiating the ITemplate in the container.
		/// </summary>
		public override void Init()
		{
			base.Init();

			this.Container.ID = this.Name;
		}
		/// <summary>
		/// Renders this template using the specified ID for the template container control.
		/// </summary>
		/// <param name="writer"></param>
		/// <param name="id"></param>
		public void Render(HtmlTextWriter writer, string id)
		{
			string saveId = this.Container.ID;
			this.Container.ID = id;
			((ContainerControl)this.Container).DoRender(writer);
			this.Container.ID = saveId;
		}
		/// <summary>
		/// Renders the script necessary to initialize the client-side template property.
		/// </summary>
		/// <param name="writer"></param>
		/// <param name="varName"></param>
		public void RenderInitScript(HtmlTextWriter writer, string varName)
		{
			writer.WriteScript("{0}.get_{1}Template().Deserialize(", varName, this.Name);
			JsonWriter jw = new JsonWriter(writer);
			this.Serialize(jw);
			writer.WriteLine(");");
		}
		#endregion
		#endregion
		#region INTERNAL
		#region METHODS
		protected override BaseTemplateContainer CreateContainer()
		{
			return new ContainerControl();
		}
		#endregion
		#endregion
		#region DECLARATIONS
		internal class ContainerControl : BaseTemplateContainer, INamingContainer
		{
			public override void DoRender(HtmlTextWriter writer)
			{
				base.RenderControl(writer);
			}
			public override void RenderControl(HtmlTextWriter writer)
			{
			}
		}
		#endregion
	}
}